package com.vbobot.demo.spring.nacos.client;

import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Bobo
 * @date 2022/9/19
 */
@RestController
public class TestController {
    @Autowired(required = false) AbstractAutoServiceRegistration<?> abstractAutoServiceRegistration;

    @GetMapping("/hello/world")
    public String helloWorld() throws InterruptedException {
        Thread.sleep(100L);
        randomThrowException();
        return "hello world";
    }

    @GetMapping("/get/with/body")
    public String getWithBody(@RequestBody GetWithBodyParam param) throws InterruptedException {
        Thread.sleep(100L);
        randomThrowException();
        return param.getName();
    }

    @PostMapping("/post/with/body")
    public String postWithBody(@RequestBody GetWithBodyParam param) throws InterruptedException {
        Thread.sleep(100L);
        randomThrowException();
        return param.getName();
    }

    private void randomThrowException() {
        new Random().nextInt(10);
        final int i = (int) (Math.random() * 10);
        if (i == 5) {
            throw new IllegalArgumentException();
        }
    }

    @GetMapping("/shutdown")
    public String shutdown() {
        abstractAutoServiceRegistration.stop();
        return "shutdown";
    }

    public static class GetWithBodyParam {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
